{% extends "members/base.html" %}

{% block title %}会员工作台{% endblock %}

{% block content %}
<!-- 工作台概览 -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-1">工作台概览</h2>
        <p class="text-muted mb-0">欢迎回来，管理您的量表和数据</p>
    </div>
    <div>
        <a href="{{ url_for('members.scale_creator') }}" class="btn btn-custom me-2">
            <i class="bi bi-plus me-1"></i>创建量表
        </a>
        <a href="{{ url_for('members.scale_library') }}" class="btn btn-outline-primary">
            <i class="bi bi-collection me-1"></i>浏览量表库
        </a>
    </div>
</div>

<!-- 统计卡片 -->
<div class="row mb-4">
    <div class="col-xl-3 col-md-6 mb-3">
        <div class="card stat-card">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="stat-icon bg-primary">
                        <i class="bi bi-journal-text"></i>
                    </div>
                    <div class="ms-3 flex-grow-1">
                        <div class="text-muted small">我的量表</div>
                        <div class="h4 mb-0">{{ stats.my_scales or 0 }}</div>
                        <small class="text-success"><i class="bi bi-arrow-up"></i> 活跃中</small>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-3">
        <div class="card stat-card">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="stat-icon bg-success">
                        <i class="bi bi-people"></i>
                    </div>
                    <div class="ms-3 flex-grow-1">
                        <div class="text-muted small">总测评数</div>
                        <div class="h4 mb-0">{{ stats.total_assessments or 0 }}</div>
                        <small class="text-success"><i class="bi bi-arrow-up"></i> 累计数据</small>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-3">
        <div class="card stat-card">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="stat-icon bg-warning">
                        <i class="bi bi-eye"></i>
                    </div>
                    <div class="ms-3 flex-grow-1">
                        <div class="text-muted small">今日浏览</div>
                        <div class="h4 mb-0">{{ stats.today_views or 0 }}</div>
                        <small class="text-info"><i class="bi bi-dash"></i> 待开发</small>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-3">
        <div class="card stat-card">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="stat-icon bg-info">
                        <i class="bi bi-heart"></i>
                    </div>
                    <div class="ms-3 flex-grow-1">
                        <div class="text-muted small">收藏次数</div>
                        <div class="h4 mb-0">{{ stats.favorites or 0 }}</div>
                        <small class="text-info"><i class="bi bi-dash"></i> 待开发</small>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 最近活动和我的量表 -->
<div class="row">
    <div class="col-lg-8">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="bi bi-activity me-2"></i>最近活动</h5>
                <a href="{{ url_for('members.records') }}" class="btn btn-outline-primary btn-sm">查看全部</a>
            </div>
            <div class="card-body">
                {% if recent_assessments %}
                    {% for assessment in recent_assessments %}
                    <div class="d-flex align-items-start mb-3">
                        <div class="bg-success rounded-circle p-2 me-3">
                            <i class="bi bi-check-circle text-white"></i>
                        </div>
                        <div class="flex-grow-1">
                            <div class="d-flex justify-content-between align-items-start">
                                <div>
                                    <h6 class="mb-1">完成测评</h6>
                                    <p class="mb-1 text-muted">{{ assessment.scale.title if assessment.scale else '未知量表' }}</p>
                                    <small class="text-muted">
                                        {{ assessment.created_at.strftime('%Y-%m-%d %H:%M') if assessment.created_at else '未知时间' }}
                                    </small>
                                </div>
                                <span class="badge bg-success">已完成</span>
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                {% else %}
                    <div class="text-center py-4">
                        <i class="bi bi-inbox text-muted" style="font-size: 3rem;"></i>
                        <p class="text-muted mt-2">暂无最近活动</p>
                        <a href="{{ url_for('members.scale_library') }}" class="btn btn-outline-primary">
                            <i class="bi bi-collection me-1"></i>浏览量表库开始测评
                        </a>
                    </div>
                {% endif %}
            </div>
        </div>
    </div>
    
    <div class="col-lg-4">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="bi bi-journal-text me-2"></i>我的量表</h5>
                <a href="{{ url_for('members.my_scales') }}" class="btn btn-outline-primary btn-sm">查看全部</a>
            </div>
            <div class="card-body">
                {% if my_scales %}
                    {% for scale in my_scales %}
                    <div class="d-flex align-items-center mb-3">
                        <div class="bg-primary rounded p-2 me-3">
                            <i class="bi bi-file-text text-white"></i>
                        </div>
                        <div class="flex-grow-1">
                            <h6 class="mb-1">{{ scale.title }}</h6>
                            <small class="text-muted">
                                创建于 {{ scale.created_at.strftime('%Y-%m-%d') if scale.created_at else '未知时间' }}
                            </small>
                        </div>
                        <span class="badge bg-{{ 'success' if scale.is_active else 'secondary' }}">
                            {{ '启用' if scale.is_active else '禁用' }}
                        </span>
                    </div>
                    {% endfor %}
                {% else %}
                    <div class="text-center py-4">
                        <i class="bi bi-plus-circle text-muted" style="font-size: 2rem;"></i>
                        <p class="text-muted mt-2 mb-0">还没有创建量表</p>
                        <a href="{{ url_for('members.scale_creator') }}" class="btn btn-outline-primary btn-sm mt-2">
                            <i class="bi bi-plus me-1"></i>创建第一个量表
                        </a>
                    </div>
                {% endif %}
            </div>
        </div>
        
        <!-- 快捷操作 -->
        <div class="card mt-3">
            <div class="card-header">
                <h5 class="mb-0"><i class="bi bi-lightning me-2"></i>快捷操作</h5>
            </div>
            <div class="card-body">
                <div class="d-grid gap-2">
                    <a href="{{ url_for('members.scale_creator') }}" class="btn btn-outline-primary">
                        <i class="bi bi-plus-circle me-2"></i>创建新量表
                    </a>
                    <a href="{{ url_for('members.scale_library') }}" class="btn btn-outline-info">
                        <i class="bi bi-collection me-2"></i>浏览量表库
                    </a>
                    <a href="{{ url_for('members.analytics') }}" class="btn btn-outline-success">
                        <i class="bi bi-bar-chart me-2"></i>数据分析
                    </a>
                    <a href="{{ url_for('members.profile') }}" class="btn btn-outline-secondary">
                        <i class="bi bi-person-gear me-2"></i>个人设置
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 会员状态提示 - 由JavaScript动态加载 -->
<div class="row mt-4" id="membershipAlert" style="display: none;">
    <div class="col-12">
        <div class="alert alert-info">
            <div class="d-flex align-items-center">
                <i class="bi bi-star-fill me-3 text-warning"></i>
                <div class="flex-grow-1" id="membershipInfo">
                    <!-- 会员信息由JavaScript填充 -->
                </div>
                <a href="{{ url_for('members.plans') }}" class="btn btn-outline-info btn-sm">
                    <i class="bi bi-arrow-up-circle me-1"></i>升级会员
                </a>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_css %}
<style>
    .stat-card {
        border: none;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        transition: transform 0.2s ease;
    }
    .stat-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0,0,0,0.15);
    }
    .stat-icon {
        width: 50px;
        height: 50px;
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.5rem;
        color: white;
    }
    .btn-custom {
        background: linear-gradient(45deg, #667eea, #764ba2);
        border: none;
        color: white;
    }
    .btn-custom:hover {
        background: linear-gradient(45deg, #5a6fd8, #6a42a0);
        color: white;
    }
    .content-area {
        padding: 0;
    }
</style>
{% endblock %}

{% block extra_js %}
<script>
    // 检查登录状态
    document.addEventListener('DOMContentLoaded', function() {
        const userToken = localStorage.getItem('userToken');
        const userInfo = localStorage.getItem('userInfo');
        
        if (!userToken) {
            // 没有token，跳转到登录页
            alert('请先登录');
            window.location.href = '{{ url_for("members.login") }}';
            return;
        }
        
        // 如果有用户信息，更新界面
        if (userInfo) {
            try {
                const user = JSON.parse(userInfo);
                updateUserInterface(user);
            } catch (e) {
                console.error('解析用户信息失败:', e);
            }
        }
        
        // 验证token有效性并获取最新用户信息
        apiRequest('/api/auth/profile')
            .then(response => {
                if (response.success) {
                    updateUserInterface(response.data.user);
                    // 更新本地存储的用户信息
                    localStorage.setItem('userInfo', JSON.stringify(response.data.user));
                } else {
                    throw new Error(response.message || 'Token验证失败');
                }
            })
            .catch(error => {
                console.error('Token验证失败:', error);
                localStorage.removeItem('userToken');
                localStorage.removeItem('userInfo');
                alert('登录已过期，请重新登录');
                window.location.href = '{{ url_for("members.login") }}';
            });
    });
    
    function updateUserInterface(user) {
        // 只更新欢迎信息，不重复更新导航栏和侧边栏（已由服务器端渲染）
        const welcomeText = document.querySelector('h2 + p');
        if (welcomeText) {
            const displayName = user.real_name || user.username || '用户';
            welcomeText.textContent = `欢迎回来，${displayName}！管理您的量表和数据`;
        }
        
        // 更新会员状态信息
        if (user.membership) {
            const membershipAlert = document.getElementById('membershipAlert');
            const membershipInfo = document.getElementById('membershipInfo');
            
            if (membershipAlert && membershipInfo) {
                let membershipHtml = `<strong>您当前是 ${user.membership.plan_type || 'basic'} 用户</strong>`;
                
                if (user.membership.end_date) {
                    const endDate = new Date(user.membership.end_date);
                    const now = new Date();
                    const diffTime = endDate - now;
                    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
                    
                    membershipHtml += `<div class="small">到期时间：${endDate.toLocaleDateString('zh-CN')}`;
                    if (diffDays <= 7 && diffDays > 0) {
                        membershipHtml += ` <span class="text-danger">（即将到期）</span>`;
                    } else if (diffDays <= 0) {
                        membershipHtml += ` <span class="text-danger">（已过期）</span>`;
                    }
                    membershipHtml += `</div>`;
                }
                
                membershipInfo.innerHTML = membershipHtml;
                membershipAlert.style.display = 'block';
            }
        }
        
        console.log('用户界面已更新:', user);
    }
</script>
{% endblock %}